<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>原生WebSocket - 用户中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            text-align: center;
        }
        
        .header h1 {
            color: #667eea;
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .user-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }
        
        .connection-status {
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: bold;
            font-size: 14px;
        }
        
        .connected {
            background: #d4edda;
            color: #155724;
            border: 2px solid #c3e6cb;
        }
        
        .disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 2px solid #f5c6cb;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }
        
        .card {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .card h2 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            border: 2px solid #eee;
        }
        
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        
        .posts-list {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .post-item {
            padding: 15px;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 10px;
            border-left: 4px solid #667eea;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .post-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        
        .post-item.unread {
            border-left-color: #ff4757;
            background: #fff5f5;
        }
        
        .post-title {
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }
        
        .post-meta {
            font-size: 0.9em;
            color: #666;
            display: flex;
            justify-content: space-between;
        }
        
        .messages {
            max-height: 300px;
            overflow-y: auto;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
        }
        
        .message {
            padding: 10px;
            margin-bottom: 10px;
            background: white;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        
        .message-time {
            font-size: 0.8em;
            color: #999;
            margin-bottom: 5px;
        }
        
        .message-content {
            color: #333;
        }
        
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        button {
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #4caf50, #45a049);
            color: white;
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #f44336, #d32f2f);
            color: white;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 10px;
            padding: 15px 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            border-left: 4px solid #667eea;
            z-index: 1000;
            max-width: 350px;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification.success {
            border-left-color: #4caf50;
        }
        
        .notification.info {
            border-left-color: #2196f3;
        }
        
        .notification.warning {
            border-left-color: #ff9800;
        }
        
        .notification.error {
            border-left-color: #f44336;
        }
        
        /* 推文通知弹窗样式 */
        .post-notification-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            animation: fadeIn 0.3s ease;
        }
        
        .post-notification-content {
            background: white;
            border-radius: 15px;
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            animation: slideIn 0.3s ease;
        }
        
        .post-notification-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 20px;
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .post-notification-header h3 {
            margin: 0;
            font-size: 1.2em;
        }
        
        .close-btn {
            background: none;
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s ease;
        }
        
        .close-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: none;
            box-shadow: none;
        }
        
        .post-notification-body {
            padding: 25px;
        }
        
        .post-notification-body h4 {
            margin: 0 0 15px 0;
            color: #333;
            font-size: 1.1em;
        }
        
        .post-notification-body p {
            margin: 0;
            color: #666;
            line-height: 1.6;
        }
        
        .post-notification-footer {
            padding: 20px 25px;
            border-top: 1px solid #eee;
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from { 
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }
            to { 
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .post-notification-content {
                width: 95%;
                margin: 20px;
            }
            
            .post-notification-footer {
                flex-direction: column;
            }
        }
            
            .stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 原生WebSocket 用户中心</h1>
            <div class="user-info">
                <span id="userName">用户: 加载中...</span>
                <div id="connectionStatus" class="connection-status disconnected">
                    🔴 未连接
                </div>
                <button class="btn-danger" onclick="logout()">退出登录</button>
            </div>
        </div>
        
        <div class="main-content">
            <!-- 推文列表 -->
            <div class="card">
                <h2>📋 推文列表</h2>
                
                <div class="stats">
                    <div class="stat-item">
                        <div class="stat-number" id="totalPosts">0</div>
                        <div class="stat-label">总推文</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="unreadPosts">0</div>
                        <div class="stat-label">未读</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="readPosts">0</div>
                        <div class="stat-label">已读</div>
                    </div>
                </div>
                
                <div class="controls">
                    <button class="btn-primary" onclick="loadPosts()">🔄 刷新推文</button>
                    <button class="btn-success" onclick="markAllRead()">✅ 全部已读</button>
                </div>
                
                <div class="posts-list" id="postsList">
                    <div class="empty-state">加载中...</div>
                </div>
            </div>
            
            <!-- WebSocket消息 -->
            <div class="card">
                <h2>📡 WebSocket 消息</h2>
                
                <div class="controls">
                    <button id="connectBtn" class="btn-success" onclick="connectWebSocket()">🔗 连接</button>
                    <button id="disconnectBtn" class="btn-danger" onclick="disconnectWebSocket()" disabled>🔌 断开</button>
                    <button class="btn-primary" onclick="clearMessages()">🗑️ 清空</button>
                </div>
                
                <div class="messages" id="messages">
                    <div class="message">
                        <div class="message-time">系统消息</div>
                        <div class="message-content">等待连接WebSocket...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 通知 -->
    <div id="notification" class="notification">
        <div id="notificationContent"></div>
    </div>

    <script>
        let currentUser = null;
        let websocket = null;
        let posts = [];
        let reconnectAttempts = 0;
        let maxReconnectAttempts = 5;
        let heartbeatInterval = null;
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('🚀 页面加载完成，开始初始化...');
            
            // 检查登录状态
            let userStr = localStorage.getItem('currentUser');
            if (!userStr) {
                console.log('❌ 未登录，尝试使用默认用户...');
                // 如果没有登录信息，使用默认用户（用于测试）
                currentUser = {
                    userId: 1,
                    userName: 'admin',
                    nickName: '管理员'
                };
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                console.log('🔧 已设置默认用户:', currentUser);
            } else {
                currentUser = JSON.parse(userStr);
                console.log('👤 当前用户:', currentUser);
            }
            
            document.getElementById('userName').textContent = `用户: ${currentUser.nickName || currentUser.userName}`;
            
            // 自动连接WebSocket
            connectWebSocket();
            
            // 加载推文列表
            loadPosts();
        });
        
        // 连接WebSocket
        function connectWebSocket() {
            try {
                console.log('🔗 准备连接WebSocket...');
                console.log('👤 当前用户信息:', currentUser);
                
                if (!currentUser || !currentUser.userId) {
                    console.error('❌ 用户信息无效，无法连接WebSocket');
                    addMessage('错误', '用户信息无效，无法连接WebSocket');
                    return;
                }
                
                const wsUrl = `ws://localhost:8077/ws/${currentUser.userId}`;
                console.log('🌐 WebSocket URL:', wsUrl);
                
                websocket = new WebSocket(wsUrl);
                
                websocket.onopen = function(event) {
                    console.log('✅ WebSocket连接已建立:', event);
                    console.log('🔗 连接状态:', websocket.readyState);
                    addMessage('连接', '✅ WebSocket连接成功');
                    updateConnectionStatus(true);
                    reconnectAttempts = 0;
                    
                    // 启动心跳
                    startHeartbeat();
                    
                    // 发送身份验证消息
                    const authMessage = {
                        type: 'auth',
                        userId: currentUser.userId,
                        userName: currentUser.userName,
                        timestamp: Date.now()
                    };
                    websocket.send(JSON.stringify(authMessage));
                    console.log('🔐 发送身份验证:', authMessage);
                    
                    showNotification('WebSocket连接成功！');
                };
                
                websocket.onmessage = function(event) {
                    console.log('📨 收到WebSocket消息:', event.data);
                    console.log('🔗 当前连接状态:', websocket.readyState);
                    
                    try {
                        const message = JSON.parse(event.data);
                        handleWebSocketMessage(message);
                    } catch (error) {
                        console.error('❌ 解析消息失败:', error);
                        addMessage('错误', '消息解析失败: ' + event.data);
                    }
                };
                
                websocket.onerror = function(error) {
                    console.error('❌ WebSocket错误:', error);
                    console.log('🔗 错误时连接状态:', websocket.readyState);
                    addMessage('错误', 'WebSocket连接错误');
                    updateConnectionStatus(false);
                };
                
                websocket.onclose = function(event) {
                    console.log('🔌 WebSocket连接关闭:', event);
                    console.log('🔗 关闭代码:', event.code, '原因:', event.reason);
                    console.log('🔗 是否正常关闭:', event.wasClean);
                    addMessage('系统', `连接关闭 (代码: ${event.code}, 原因: ${event.reason || '未知'})`);
                    updateConnectionStatus(false);
                    
                    // 自动重连
                    if (reconnectAttempts < maxReconnectAttempts) {
                        reconnectAttempts++;
                        const delay = Math.min(1000 * reconnectAttempts, 10000);
                        console.log(`🔄 ${delay/1000}秒后尝试第${reconnectAttempts}次重连...`);
                        setTimeout(connectWebSocket, delay);
                    } else {
                        addMessage('系统', '❌ 达到最大重连次数，请手动重连');
                    }
                };
                
            } catch (error) {
                console.error('❌ 创建WebSocket失败:', error);
                addMessage('错误', '创建WebSocket连接失败: ' + error.message);
                updateConnectionStatus(false);
            }
        }
        
        // 断开WebSocket
        function disconnectWebSocket() {
            if (websocket) {
                websocket.close();
                websocket = null;
            }
            
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
                heartbeatInterval = null;
            }
            
            updateConnectionStatus(false);
            addMessage('系统', '手动断开连接');
            reconnectAttempts = maxReconnectAttempts; // 阻止自动重连
        }
        
        // 处理WebSocket消息
        function handleWebSocketMessage(message) {
            console.log('🔄 处理消息:', message);
            
            switch (message.type) {
                case 'new_post':
                    console.log('📝 收到新推文通知:', message.title, 'PostID:', message.postId);
                    addMessage('新推文', `📝 ${message.title}`);
                    
                    // 显示弹窗通知（传递postId）
                    showPostNotification(message.title, message.message, message.postId);
                    
                    // 自动刷新推文列表
                    console.log('🔄 开始自动刷新推文列表...');
                    loadPosts().then(() => {
                        console.log('✅ 推文列表自动刷新完成');
                    }).catch(error => {
                        console.error('❌ 自动刷新推文列表失败:', error);
                    });
                    break;
                    
                case 'unread_count':
                    console.log('📊 收到未读数量更新:', message.count);
                    addMessage('统计', `📊 未读数量: ${message.count}`);
                    updateUnreadCount(message.count);
                    break;
                    
                case 'broadcast':
                    console.log('📢 收到广播消息:', message.message);
                    addMessage('广播', `📢 ${message.message}`);
                    showNotification(`系统广播: ${message.message}`, 'info');
                    break;
                    
                case 'heartbeat_response':
                case 'heartbeat':
                    console.log('💓 收到心跳响应');
                    break;
                    
                case 'connection':
                    console.log('🔗 连接确认:', message.message);
                    addMessage('连接', message.message);
                    break;
                    
                case 'auth_success':
                    console.log('🔐 身份验证成功:', message.message);
                    addMessage('认证', message.message);
                    break;
                    
                default:
                    console.log('❓ 收到未知类型消息:', message);
                    addMessage('消息', message.message || JSON.stringify(message));
                    showNotification('收到新消息', 'info');
            }
        }
        
        // 启动心跳
        function startHeartbeat() {
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
            }
            
            heartbeatInterval = setInterval(function() {
                if (websocket && websocket.readyState === WebSocket.OPEN) {
                    const heartbeat = {
                        type: 'heartbeat',
                        userId: currentUser.userId,
                        timestamp: Date.now()
                    };
                    websocket.send(JSON.stringify(heartbeat));
                    console.log('💓 发送心跳');
                }
            }, 30000); // 每30秒发送心跳
        }
        
        // 更新连接状态
        function updateConnectionStatus(connected) {
            const statusEl = document.getElementById('connectionStatus');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            
            if (connected) {
                statusEl.textContent = '🟢 已连接';
                statusEl.className = 'connection-status connected';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
            } else {
                statusEl.textContent = '🔴 未连接';
                statusEl.className = 'connection-status disconnected';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                
                if (heartbeatInterval) {
                    clearInterval(heartbeatInterval);
                    heartbeatInterval = null;
                }
            }
        }
        
        // 添加消息到消息列表
        function addMessage(type, content) {
            const messagesEl = document.getElementById('messages');
            const messageEl = document.createElement('div');
            messageEl.className = 'message';
            
            const time = new Date().toLocaleTimeString();
            messageEl.innerHTML = `
                <div class="message-time">${time} - ${type}</div>
                <div class="message-content">${content}</div>
            `;
            
            messagesEl.appendChild(messageEl);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }
        
        // 清空消息
        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
            addMessage('系统', '消息已清空');
        }
        
        // 显示通知
        function showNotification(message, type = 'success') {
            const notification = document.getElementById('notification');
            const content = document.getElementById('notificationContent');
            
            content.textContent = message;
            notification.className = `notification ${type} show`;
            
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }
        
        // 显示推文通知弹窗
        function showPostNotification(title, content, postId) {
            // 创建推文通知弹窗
            const modal = document.createElement('div');
            modal.className = 'post-notification-modal';
            modal.innerHTML = `
                <div class="post-notification-content">
                    <div class="post-notification-header">
                        <h3>📝 新推文通知</h3>
                        <button class="close-btn" onclick="this.parentElement.parentElement.parentElement.remove()">×</button>
                    </div>
                    <div class="post-notification-body">
                        <h4>${title}</h4>
                        <p>${content}</p>
                    </div>
                    <div class="post-notification-footer">
                        <button class="btn-primary" onclick="viewPost(${postId}); this.parentElement.parentElement.parentElement.remove();">查看推文</button>
                        <button class="btn-secondary" onclick="this.parentElement.parentElement.parentElement.remove();">稍后查看</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // 播放通知音效（如果浏览器支持）
            try {
                const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT');
                audio.play().catch(() => {}); // 忽略播放失败
            } catch (e) {}
            
            // 8秒后自动关闭
            setTimeout(() => {
                if (modal.parentNode) {
                    modal.remove();
                }
            }, 8000);
        }
        
        // 更新未读数量显示
        function updateUnreadCount(count) {
            const unreadEl = document.getElementById('unreadPosts');
            if (unreadEl) {
                unreadEl.textContent = count;
                
                // 如果有未读消息，添加闪烁效果
                if (count > 0) {
                    unreadEl.style.animation = 'pulse 1s ease-in-out 3';
                } else {
                    unreadEl.style.animation = '';
                }
            }
        }
        
        // 加载推文列表
        async function loadPosts() {
            try {
                console.log('📋 开始加载推文列表...');
                const response = await fetch(`/api/posts/user/${currentUser.userId}`);
                const result = await response.json();
                
                if (result.success) {
                    posts = result.data;
                    renderPosts();
                    updateStats();
                    console.log('📋 推文列表加载成功:', posts.length);
                } else {
                    console.error('❌ 加载推文失败:', result.message);
                    document.getElementById('postsList').innerHTML = 
                        '<div class="empty-state">加载失败: ' + result.message + '</div>';
                }
            } catch (error) {
                console.error('❌ 加载推文异常:', error);
                document.getElementById('postsList').innerHTML = 
                    '<div class="empty-state">网络错误，请重试</div>';
            }
        }
        
        // 渲染推文列表
        function renderPosts() {
            const postsListEl = document.getElementById('postsList');
            
            if (posts.length === 0) {
                postsListEl.innerHTML = '<div class="empty-state">📭 暂无推文</div>';
                return;
            }
            
            const postsHtml = posts.map(post => `
                <div class="post-item ${post.isRead === 0 ? 'unread' : ''}" onclick="viewPost(${post.postId})">
                    <div class="post-title">${post.title}</div>
                    <div class="post-meta">
                        <span>👤 ${post.authorName}</span>
                        <span>🕒 ${formatTime(post.publishTime)}</span>
                        <span>${post.isRead === 1 ? '✅ 已读' : '🔴 未读'}</span>
                    </div>
                </div>
            `).join('');
            
            postsListEl.innerHTML = postsHtml;
        }
        
        // 更新统计信息
        function updateStats() {
            const total = posts.length;
            const unread = posts.filter(post => post.isRead === 0).length;
            const read = total - unread;
            
            document.getElementById('totalPosts').textContent = total;
            document.getElementById('unreadPosts').textContent = unread;
            document.getElementById('readPosts').textContent = read;
        }
        
        // 更新未读数量
        function updateUnreadCount(count) {
            document.getElementById('unreadPosts').textContent = count;
        }
        
        // 查看推文详情
        async function viewPost(postId) {
            try {
                console.log('🔍 查看推文详情，ID:', postId);
                
                // 调用后端API获取完整推文详情
                const response = await fetch(`/api/posts/${postId}`);
                const result = await response.json();
                
                console.log('📖 推文详情响应:', result);
                
                if (result.success && result.data) {
                    const post = result.data;
                    
                    // 显示推文详情
                    const detailContent = `📖 推文详情

📝 标题: ${post.title}

📄 内容: ${post.content || '暂无内容'}

📋 摘要: ${post.summary || '暂无摘要'}

👤 作者: ${post.authorName}
🕒 发布时间: ${formatTime(post.publishTime)}
👀 浏览量: ${post.viewCount || 0}
👍 点赞数: ${post.likeCount || 0}
💬 评论数: ${post.commentCount || 0}`;
                    
                    alert(detailContent);
                    
                    // 标记为已读
                    await markAsRead(postId);
                } else {
                    console.error('❌ 获取推文详情失败:', result.message);
                    alert('获取推文详情失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('❌ 查看推文失败:', error);
                alert('查看推文失败，请检查网络连接');
            }
        }
        
        // 标记为已读
        async function markAsRead(postId) {
            try {
                console.log('✅ 标记推文为已读，ID:', postId, '用户ID:', currentUser.userId);
                
                const response = await fetch(`/api/posts/${postId}/read?userId=${currentUser.userId}`, {
                    method: 'POST'
                });
                const result = await response.json();
                
                console.log('✅ 标记已读响应:', result);
                
                if (result.success) {
                    // 更新本地数据
                    const post = posts.find(p => p.postId === postId);
                    if (post) {
                        post.isRead = 1; // 设置为已读状态
                    }
                    renderPosts();
                    updateStats();
                    showNotification('已标记为已读');
                } else {
                    console.error('❌ 标记已读失败:', result.message);
                    alert('标记已读失败: ' + result.message);
                }
            } catch (error) {
                console.error('❌ 标记已读异常:', error);
                alert('标记已读失败，请重试');
            }
        }
        
        // 全部标记为已读
        async function markAllRead() {
            const unreadPosts = posts.filter(post => post.isRead === 0);
            if (unreadPosts.length === 0) {
                showNotification('没有未读推文');
                return;
            }
            
            for (const post of unreadPosts) {
                await markAsRead(post.postId);
            }
            
            showNotification(`已标记 ${unreadPosts.length} 条推文为已读`);
        }
        
        // 格式化时间
        function formatTime(timeStr) {
            const date = new Date(timeStr);
            const now = new Date();
            const diff = now - date;
            
            if (diff < 60000) return '刚刚';
            if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
            if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
            return Math.floor(diff / 86400000) + '天前';
        }
        
        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                if (websocket) {
                    websocket.close();
                }
                window.location.href = '/index.html';
            }
        }
        
        // 页面卸载时清理
        window.addEventListener('beforeunload', function() {
            if (websocket) {
                websocket.close();
            }
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
            }
        });
    </script>
</body>
</html>